package petrov.kristiyan.colorpicker;

import ohos.app.Context;
import ohos.global.configuration.DeviceCapability;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;

import java.io.IOException;

/**
 * @author Kristiyan Petrov
 */
public class ColorUtils {
    /**
     * Returns true if the text color should be white, given a background color
     *
     * @param color background color
     * @return true if the text should be white, false if the text should be black
     */
    public static boolean isWhiteText(final int color) {
        final int red = red(color);
        final int green = green(color);
        final int blue = blue(color);

        // https://en.wikipedia.org/wiki/YIQ
        // https://24ways.org/2010/calculating-color-contrast/
        final int yiq = ((red * 299) + (green * 587) + (blue * 114)) / 1000;
        return yiq < 192;
    }

    /**
     * 根据资源id获取vp值
     * @param resId
     * @param context
     * @return int
     */
    public static int getDimensionDp(int resId, Context context) {
        try {
            int density = context.getResourceManager().getDeviceCapability().screenDensity / DeviceCapability.SCREEN_MDPI;
            return (int) (context.getResourceManager().getElement(resId).getFloat() / density);
        } catch (IOException | NotExistException | WrongTypeException e) {
            e.fillInStackTrace();
            return 0;
        }
    }

    /**
     * 根据vp转换为px
     * @param size
     * @param context
     * @return int
     */
    public static int dip2px(float size, Context context) {
        int density = context.getResourceManager().getDeviceCapability().screenDensity / DeviceCapability.SCREEN_MDPI;
        return (int) (size * density + 0.5d);
    }

    /**
     * 获取颜色中的红色
     * @param color
     * @return int
     */
    public static int red(int color) {
        return (color >> 16) & 0xFF;
    }

    /**
     * 获取颜色中的绿色
     * @param color
     * @return int
     */
    public static int green(int color) {
        return (color >> 8) & 0xFF;
    }

    /**
     * 获取颜色中的蓝色
     * @param color
     * @return int
     */
    public static int blue(int color) {
        return color & 0xFF;
    }
}
